package com.topisv.tms.web.stock.instorage;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.stock.instorage.InstorageCountItem;
import com.topisv.tms.entity.stock.instorage.InstorageUpSubTaskItem;
import com.topisv.tms.entity.stock.instorage.InstorageUpTask;
import com.topisv.tms.entity.stock.instorage.InstorageUpTaskItem;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.stock.instorage.InstorageCountTaskService;
import com.topisv.tms.service.stock.instorage.InstorageUpDispatchTaskService;
import com.topisv.tms.service.stock.instorage.InstorageUpTaskService;
import com.topisv.tms.service.work.WorkTaskService;

/**
 * 入库上架_control
 * @author ch
 */
@Controller
@RequestMapping(value = "/v2_instorageUp")
public class InstorageUpController {

	private static final Logger logger = LoggerFactory.getLogger(InstorageUpController.class);

	@Autowired
	private CustomersService customersService;
	@Autowired
	private InstorageCountTaskService instorageCountTaskService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private InstorageUpTaskService instorageUpTaskService;
	@Autowired
	private InstorageUpDispatchTaskService instorageUpDispatchTaskService;
	@Autowired
    private EdiGoodsSkuService ediGoodsSkuService;
	@Autowired
    private WorkTaskService workTaskService;

	/**
	 * 导向上架任务列表页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "toUpTaskListPage")
	public String toUpTaskListPage(ServletRequest request,HttpServletResponse response,Model model){
		try {
			
			//当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("upcustomerList",customerList);
			model.addAttribute("userType",curUser.userType);
		    
		    //我的任务
		    Map<String, Object> param_my=new HashMap<String, Object>();
		    param_my.put("workerUuid", curUser.jobuuid);
		    param_my.put("status", "myTask"); //任务状态 （undo.创建上架任务 token:领取任务 doing:上架中 finish.上架完成）
		    List<InstorageUpTask> myTaskList=this.instorageUpTaskService.loadTaskByParam(param_my);
		    model.addAttribute("myTaskList",myTaskList);
		    
		    //如果是派友用户,初始化数据
			if("paiu".equals(curUser.userType)){
				//未分配的上架任务
			    Map<String, Object> param=new HashMap<String, Object>();
			    param.put("customerCodes", StringUtils.isBlank(curUser.customers)?"blank":curUser.customers);
			    param.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
			    param.put("status", "undo"); //任务状态 （undo.创建上架任务 token:领取任务 doing:上架中 finish.上架完成）
			    List<InstorageUpTask> untakedTaskList=this.instorageUpTaskService.loadTaskByParam(param);
			    model.addAttribute("untakedTaskList",untakedTaskList);
			    
			}
		    
		    //如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				//未分配的上架任务
				String customerCode=curUser.customerCode;
			    Map<String, Object> param=new HashMap<String, Object>();
			    param.put("customerCodes", StringUtils.isBlank(customerCode)?"blank":customerCode);
			    param.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
			    param.put("status", "undo"); //任务状态 （undo.创建上架任务 token:领取任务 doing:上架中 finish.上架完成）
			    List<InstorageUpTask> untakedTaskList=this.instorageUpTaskService.loadTaskByParam(param);
			    model.addAttribute("untakedTaskList",untakedTaskList);
			    
			    //初始化仓库数据
				if(StringUtils.isNotBlank(customerCode)){
					List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
					model.addAttribute("warehouseList", warehouseList);
					model.addAttribute("upwarehouseList", warehouseList);
				}
			}
		
		} catch (Exception e) {
			
			logger.error("error",e);
		}
	    
		return "instorage/instorageUpTaskList";
	}
	
	
	/**
	 * 查询上架任务列表
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "queryTaskList",method = RequestMethod.POST)
	public void queryTaskList(ServletRequest request,HttpServletResponse response) throws Exception {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		    //查询未分配的拣货任务
			String warehouseCode=request.getParameter("warehouseCode");
			String customerCode=request.getParameter("customerCode");
			Map<String, Object> param=new HashMap<String, Object>();
			if(StringUtils.isBlank(customerCode)){
				param.put("customerCodes", this.customersService.loadCustomerByAuthority(curUser.jobuuid));
			}else{
				param.put("customerCodes", customerCode);
			}
			
			if(StringUtils.isBlank(warehouseCode)){
				param.put("areagroups", curUser.areagroups);
			}else{
				param.put("areagroups", warehouseCode);
			}
			
			param.put("status", "undo");
			List<InstorageUpTask> untakedTaskList=this.instorageUpTaskService.loadTaskByParam(param);
			json.put("status","success");
			json.put("untakedTaskList",untakedTaskList);
			
		} catch (Exception e) {
			logger.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());
		}

		out.print(json.toString());
	}
	@RequestMapping(value = "queryMyTaskList",method = RequestMethod.POST)
	public void queryMyTaskList(ServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			//我的任务 
			Map<String, Object> param_my=new HashMap<String, Object>();
			String upwarehouseCode=request.getParameter("upwarehouseCode");
			String upcustomerCode=request.getParameter("upcustomerCode");
			String upstatus=request.getParameter("upstatus");
			String upbillCode=request.getParameter("upbillCode");
			if(StringUtils.isBlank(upcustomerCode)){
				param_my.put("customerCodes", this.customersService.loadCustomerByAuthority(curUser.jobuuid));
			}else{
				param_my.put("customerCodes", upcustomerCode);
			}
			
			if(StringUtils.isBlank(upwarehouseCode)){
				param_my.put("areagroups", curUser.areagroups);
			}else{
				param_my.put("areagroups", upwarehouseCode);
			}
			if(StringUtils.isBlank(upstatus)){
				param_my.put("upstatus", "");
				
			}else{
				param_my.put("upstatus", upstatus);
			}
			if(StringUtils.isBlank(upbillCode)){
				param_my.put("upbillCode", "");
			}else{
				param_my.put("upbillCode", upbillCode);
			}
			param_my.put("workerUuid", curUser.jobuuid);
			param_my.put("status", "myTask"); //任务状态 （undo.创建点收任务 doing:点收中 finish.点收完成）
		    List<InstorageUpTask> myTaskList=this.instorageUpTaskService.loadTaskByParam(param_my);
		    json.put("status","success");
			json.put("myTaskList",myTaskList);
		
		} catch (Exception e) {
			logger.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());
		}
		out.print(json.toString());
	}
	/**
	 * 领取任务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxTakeTask")
	@ResponseBody
	public String ajaxTakeTask(ServletRequest request,HttpServletResponse response) {
	    boolean isLockSuccess = false;
	    Long taskId=Long.valueOf(request.getParameter("taskId")+""); 
		try {
		    isLockSuccess = workTaskService.lock("instorageUpC.ajaxTakeTask", taskId+"", "-");
            if (!isLockSuccess) {
                return "false";
            }
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			//领取任务
			this.instorageUpTaskService.takeTask(taskId,curUser.jobuuid);
			
			return "true";
		} catch (Exception e) {
			logger.error("error",e);
			return "false";
		} finally {
            if (isLockSuccess) {
                workTaskService.releaseLock("instorageUpC.ajaxTakeTask", taskId+"");
            }
        }
	}
	
	/**
	 * 导向上架页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toInstorageUpPage/{taskId}", method = RequestMethod.GET)
	public String toInstorageUpPage(@PathVariable("taskId") Long taskId, Model model) {
		try {
		      InstorageUpTask  task=this.instorageUpTaskService.loadById(taskId);
		      model.addAttribute("task", task);
		      
		      String taskType=task.getTaskType();
		      if("box".equals(taskType)){
		    	  
		    	  List<InstorageCountItem> itemList=this.instorageCountTaskService.loadByUpTaskCode(task.getTaskCode());
		    	  model.addAttribute("itemList",itemList);
		    	  return "instorage/instorageUp_box"; //整箱上架
		    	  
		      }else if("single".equals(taskType)){ 
		    	  
		    	  List<InstorageCountItem> itemList=this.instorageCountTaskService.loadByUpTaskCode(task.getTaskCode());
		    	  model.addAttribute("itemList",itemList);
		    	  return "instorage/instorageUp_single"; //散货上架
		    	  
		      }
		      
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return  null;
		
	}
	
	
	/**
	 * 导向上架页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toInstorageUpPageNew/{taskId}", method = RequestMethod.GET)
	public String toInstorageUpPageNew(@PathVariable("taskId") Long taskId, Model model) {
		try {
			InstorageUpTask task = this.instorageUpTaskService.loadById(taskId);
			model.addAttribute("task", task);
			List<InstorageUpTaskItem> itemList = this.instorageUpTaskService.findByTaskCode(task.getTaskCode());
			model.addAttribute("itemList", itemList);
			
			List<InstorageUpSubTaskItem> unUpItem = instorageUpDispatchTaskService.unUpDispatchItem(task.getTaskCode());
			model.addAttribute("unUpItem", unUpItem);
			return "instorage/instorageUp"; 
		} catch (Exception e) {
			logger.error("error", e);
		}
		return null;
	}
	@RequestMapping(value = "deleteItem/{taskId}/{itemId}", method = RequestMethod.GET)
	public String deleteItem(@PathVariable("taskId") Long taskId,@PathVariable("itemId") Long itemId){
		instorageUpTaskService.deleteItem(itemId);
		return "redirect:/v2_instorageUp/toInstorageUpPageNew/" + taskId;
	}
	
	@RequestMapping(value = "ajaxUpNew/{taskId}")
	public void ajaxUpNew(@PathVariable("taskId") Long taskId, InstorageUpTaskItem taskItem,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		boolean isLockSuccess = false;
		
		try {
		    json = new JSONObject();
		    out = response.getWriter();
		    
		    isLockSuccess = workTaskService.lock("instorageUpC.ajaxUpNew", taskId+"", "-");
            if (!isLockSuccess) {
                json.put("status", "error");
                json.put("msg", "当前任务正在处理，请勿重复操作！");
                return;
            }
			
			
			/**add 上架过程中将不在收货任务中的sku识别出来，增加提示 bug404 by zhangweize   L318-329（除了323)\L335-337*/
			//判断上架的SKU是否在分配上架子任务明细中
			boolean isExist = instorageUpTaskService.checkUpSku(taskItem);
			
			if (isExist) {
				//上架
				instorageUpTaskService.upNew(taskItem);
				json.put("status", "success");
				json.put("msg", "上架");
			} else {
				json.put("status", "error");
				json.put("msg", "该sku不在当前任务中,请核对");
			}
		} catch (Exception e) {

			json.put("status", "error");
            if (e instanceof PaiUException) {
                json.put("msg", e.getMessage());
            } else {
                json.put("msg", "上架失败");
            }
			logger.error("error", e);
		} finally {
		    if (isLockSuccess) {
                workTaskService.releaseLock("instorageUpC.ajaxUpNew", taskId+"");
            }
			out.print(json.toString());
		}
	}
	
	@RequestMapping(value = "finishUpTask/{taskCode}")
	public void finishUpTask(@PathVariable("taskCode") String taskCode,HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		String msg = null;
	    boolean isLockSuccess = false;

		try {
			json = new JSONObject();
			out = response.getWriter();
			
			isLockSuccess = workTaskService.lock("instorageUpC.finishUpTask", taskCode, "-");
            if (!isLockSuccess) {
                msg = "false";
                return;
            }
            
			//上架
			msg = instorageUpTaskService.finishUpTask(taskCode);
		} catch(PaiUException ex){
		    logger.error("error",ex);
		    msg = "notMatch";
		} catch (Exception e) {
			logger.error("error.",e);
			msg = "false";
		} finally {
            if (isLockSuccess) {
                workTaskService.releaseLock("instorageUpC.finishUpTask", taskCode);
            }
            json.put("msg", msg);
            out.print(json.toString());
        }
		
	}
	
	
	
	/**
	 * 整箱上架
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "ajaxUp_box")
	public void ajaxUp_box(ServletRequest request,HttpServletResponse response) {
	    String uptaskCode=request.getParameter("uptaskCode");
	    String boxCode=request.getParameter("boxCode");
	    String stockCode=request.getParameter("stockCode");
	    
		JSONObject json = null;
		PrintWriter out = null;

		boolean isLockSuccess = false;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			isLockSuccess = workTaskService.lock("instorageUpC.ajaxUp_box", uptaskCode, "-");
            if (!isLockSuccess) {
                json.put("msg", "error");
                return;
            }
			
			//上架
			String msg=this.instorageUpTaskService.up_box(uptaskCode,boxCode,stockCode);
			json.put("msg", msg);
			
		} catch (Exception e) {
			
			json.put("msg","error");
			logger.error("error",e);
		} finally {
            if (isLockSuccess) {
                workTaskService.releaseLock("instorageUpC.ajaxUp_box", uptaskCode);
            }
            out.print(json.toString());
        }
	}
	
	/**
	 * 散货上架
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "ajaxUp_single")
	public void ajaxUp_single(ServletRequest request,HttpServletResponse response) {
	    String uptaskCode=request.getParameter("uptaskCode");
	    String sku=request.getParameter("sku");
	    String stockCode=request.getParameter("stockCode");
	    String boxCode=request.getParameter("boxCode");

		JSONObject json = null;
		PrintWriter out = null;
		boolean isLockSuccess = false;
		
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			isLockSuccess = workTaskService.lock("instorageUpC.ajaxUp_single", uptaskCode, "-");
            if (!isLockSuccess) {
                json.put("msg", "error");
                return;
            }
            
			//上架
			String msg=this.instorageUpTaskService.up_single(uptaskCode,sku,stockCode,boxCode);
			json.put("msg", msg);
			
			//任务明细
			List<InstorageCountItem> itemList=this.instorageCountTaskService.loadByUpTaskCode(uptaskCode);
			json.put("itemList", itemList);
			
		} catch (Exception e) {
			
			json.put("msg","error");
			logger.error("error",e);
		} finally {
            if (isLockSuccess) {
                workTaskService.releaseLock("instorageUpC.ajaxUp_single", uptaskCode);
            }
            out.print(json.toString());
        }
	}
	
	/**
     * 验证SKU
     * @param request
     * @param response
     */
    @RequestMapping(value = "findSku")
    public void findSku(ServletRequest request,HttpServletResponse response) {

        JSONObject json = null;
        PrintWriter out = null;
        try {
            json = new JSONObject();
            out = response.getWriter();
            
            //获取参数
            String subTaskCode=request.getParameter("subTaskCode");
            String sku=request.getParameter("sku");
            String customerCode=request.getParameter("customerCode");
            
            EdiGoodsSku ediGoodsSku = this.ediGoodsSkuService.findByCustomerCodeAndSku(customerCode, sku);
            //add LiBin bug617 防止界面输入的数据和数据库中存在大小写的区别
            if(ediGoodsSku == null || !ediGoodsSku.getSku().equals(sku)){
                json.put("status","skuNotExist");
                json.put("content","SKU不存在(查看大小写)!");
                logger.error("---------sku :"+sku+" not exist!-----");
            }else {
                json.put("status", "success");
                json.put("isBatchMgmt", ediGoodsSku.getIsBatchMgmt() == null ? "0" : ediGoodsSku.getIsBatchMgmt());
                json.put("isShelfLifeMgmt", ediGoodsSku.getIsShelfLifeMgmt() == null? "0" : ediGoodsSku.getIsShelfLifeMgmt());
                
                json.put("batchList",this.instorageUpTaskService.batchList(subTaskCode, sku));
                
            }
        } catch (Exception e) {
            json.put("status","error");
            json.put("content",e.getMessage());
            logger.error("error",e);
        }
        out.print(json.toString());
    }
	
}
